/**
 * <pre>
 * 紫光软件系统有限公司广电事业部
 * Copyright (C): 2012
 * 
 * 文件名称：
 * com.unis.iptv.dao.impl.ChannelDaoImpl.java
 * 
 * 文件描述: 
 * TODO
 * 
 * Notes:
 * 修改历史(作者/日期/改动描述):
 * 杨飞宇/2012-8-20/初始化版本。
 * </pre>
 */
package com.unis.iptv.dao.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;

import com.unis.iptv.common.jdbc.BaseDao;
import com.unis.iptv.common.utils.GlobalUtil;
import com.unis.iptv.dao.ChannelDao;
import com.unis.iptv.domain.Channel;

/**
 * @date 2012-8-20
 * @author 杨飞宇
 */
@Repository
public class ChannelDaoImpl extends BaseDao implements ChannelDao {
	
	@Override
	public boolean saveChannel(Channel channel) {
		int result = 0;
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO TBL_"
				+ GlobalUtil.areaAlias
				+ "_CHANNEL(CHANNEL_ID,CHANNEL_NUMBER,CHANNEL_NAME,INSERT_TIME,PLAY_LINK,TEM_ID,CRAWLER_NUM)VALUES(?,?,?,SYSDATE,?,?,?)");
		String finalSql = sql.toString();
		result = jdbcTemplate.update(
				finalSql,
				new Object[] { channel.getChannelId(),
						channel.getChannelNumber(), channel.getChannelName(),
						channel.getPlayLink(), GlobalUtil.temId,
						GlobalUtil.crawlerNum });
		if (result > 0) {
			return true;
		}
		return false;
	}
	
	@Override
	public int saveChannelList(List<Channel> channels) {
		final List<Channel> tempChannels = channels;
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO TBL_"
				+ GlobalUtil.areaAlias
				+ "_CHANNEL(CHANNEL_ID,CHANNEL_NUMBER,CHANNEL_NAME,INSERT_TIME,PLAY_LINK,TEM_ID,CRAWLER_NUM)VALUES(?,?,?,SYSDATE,?,?,?)");
		String finalSql = sql.toString();
		int[] result = jdbcTemplate.batchUpdate(finalSql,
				new BatchPreparedStatementSetter() {
					
					@Override
					public void setValues(PreparedStatement preparedstatement,
							int i) throws SQLException {
						int channelId = tempChannels.get(i).getChannelId();
						String channelNumber = tempChannels.get(i)
								.getChannelNumber();
						String channelName = tempChannels.get(i)
								.getChannelName();
						String playLink = tempChannels.get(i).getPlayLink();
						int temId = GlobalUtil.temId;
						String crawlerNum = GlobalUtil.crawlerNum;
						preparedstatement.setInt(1, channelId);
						preparedstatement.setString(2, channelNumber);
						preparedstatement.setString(3, channelName);
						preparedstatement.setString(4, playLink);
						preparedstatement.setInt(5, temId);
						preparedstatement.setString(6, crawlerNum);
					}
					
					@Override
					public int getBatchSize() {
						return tempChannels.size();
					}
				});
		
		return result.length;
	}
	
	@Override
	public int getChannelId() {
		return getIdByAlias("channel");
	}
}
